// packageLive/pages/cutPrice/detail/detail.js
var util = require('../../../../utils/util') //引入配置接口文件
import { spellApi, QRCode } from '../../../../config/config'
var configUrl = require('../../../../config/config') //引入配置接口文件
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    statusHeight: app.globalData.StatusBar,
    imgUrl: getApp().globalData.imgUrl,
    returnTime: {
      day: '00',
      hours: '00',
      minute: '00',
      second: '00'
    },
    tipsInfo: '',
    friendsList: [],
    cutPriceDlg: false,
    seeMore: false,
    activityRuleDlg: false,
    activityShareDlg: false,
    cutAKnifeDlg: false,
    cutAKnifeFailedDlg: false,
    cutAKnifeFailedMsg: '',
    groupId: '',
     /**-合伙人--*/
     isShowPartnerAll: 1,
     timer: "",                                                     // 倒计时定时器名称
     showPartnerCodePop: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if (!wx.getStorageSync('addrCode').provinceCode) {
      app.getUserLocation() //初始化获取定位地址
    }
    if (!wx.getStorageSync('loginMsg').token) {
      app.initLogin() //初始化登录
    }
    var temporaryAddressData = wx.getStorageSync('temporaryAddressData')
    var parms = {
      areaCode: wx.getStorageSync('addrCode').provinceCode
    }
    if (options.scene || options.hid) {
      var scene = options.hid ? options.hid : decodeURIComponent(options.scene) //参数二维码传递过来的参数
      if (options.scene) {
        app.getShareCode(scene, (res) => {
          that.setData({
            temporaryAddressData: temporaryAddressData,
            groupId: res.id
          })
          parms.id = res.id
          var stInFun = setInterval(() => {
            if (wx.getStorageSync('getLocation') === 'N') {
              that.setData({
                showSetting: true
              })
            }
            if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
              that.setData({
                showSetting: false
              })
              clearInterval(stInFun)
              if (!wx.getStorageSync('loginMsg').loginState) {
                if (wx.getUserProfile) {
                  app.getUserProfile(function(){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  })
                } else {
                  if(!wx.getStorageSync('loginMsg').bindingPhone){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  }
                }
                // this.setData({
                //   isShowGetUserInfo: true
                // })
              }
              app.bindingPartner(res.userId)
              that.getDetail(parms.id)
            }
          }, 500)
        })
      } else if (options.hid) {
        var shareData={userId:options.hid}
        wx.setStorageSync('shearData', shareData)
        that.setData({
          groupId: options.id
        })
        parms.id = options.id
        var stInFun = setInterval(() => {
          if (wx.getStorageSync('getLocation') === 'N') {
            that.setData({
              showSetting: true
            })
          }
          if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
            that.setData({
              showSetting: false
            })
            clearInterval(stInFun)
            if (!wx.getStorageSync('loginMsg').loginState) {
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                } else {
                  callback(true)  //低版本微信绑过电话视为已登录
                }
              }
              // this.setData({
              //   isShowGetUserInfo: true
              // })
            }
            app.bindingPartner(options.hid)
            that.getDetail(parms.id)
          }
        }, 500)
      }
    } else {
      this.setData({
        temporaryAddressData: temporaryAddressData,
        groupId: options.id
      })
      if (options.data) {
        let optionData = JSON.parse(options.data)
        this.setData({
          tipsInfo: optionData
        })
      }
      if (options.id) {
        this.setData({
          groupId: options.id
        })
        this.getDetail(options.id)
      }
    }
  },
  goreBack: function (e) { //返回
    wx.navigateBack({
      delta: 1
    })
  },
  goHome: function (e) { //返回主页
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  getScroll(e) { //监听滑动
    var scorll = e.detail.scrollTop
    if (scorll > 50 && scorll < 150) {
      this.setData({
        headerClass: 'headerClass1',
        tableIsHidden: false,
        returnBoxgo: 'returnBoxgo'
      });
    } else if (scorll > 150) {
      this.setData({
        headerClass: 'headerClass2',
        tableIsHidden: false,
        returnBoxgo: 'returnBoxgo',
      });
    } else if (scorll < 50) {
      this.setData({
        headerClass: 'headerClass3',
        tableIsHidden: true,
        returnBoxgo: '',
      });
    }
    if (scorll < 500) {
      this.setData({
        fontText: 1
      });
    } else if (scorll > 500 && scorll < 1100) {
      this.setData({
        fontText: 2
      });
    } else {
      this.setData({
        fontText: 3
      });
    }
  },
  activityRule() {
    this.setData({
      activityRuleDlg: true
    })
  },
  onClose() {
    this.setData({ cutPriceDlg: false })
  },
  ruleOnClose() {
    this.setData({ activityRuleDlg: false })
  },
  activityShareClose() {
    this.setData({ activityShareDlg: false })
  },
  // 获取详情信息
  getDetail(id) {
    let cutPriceGroupId = id
    app.reqFun.requestJson('GET',spellApi.cutPriceDetail+cutPriceGroupId,'',(res)=>{
      if(res.data.success === 1) {
        let data = res.data.data
        data.ruleText = data.ruleText.replace(/<img/g, "<img style='width:100%;height:auto;'").replace(/http:\/\//g, 'https://')
        this.setData({
          friends: data.friends
        })
        this.getReturnTime(data.endTime)
        let friends = data.friends
        if (friends) {
          // if (friends.length > 3) {
          //   friends.length = 3
          //   this.setData({
          //     seeMore: true
          //   })
          // }
        }
        this.setData({
          detailData: data,
          friendsList: friends
        })
        if (this.data.tipsInfo.firstCutFlag && this.data.tipsInfo.remainingCutPrice != 0) {
          this.setData({
            cutPriceDlg: true
          })
        }
      }
    })
  },
  //处理活动倒计时--time=活动结束时间
  getReturnTime(time) { //处理活动倒计时--time=活动结束时间
    let that = this;
        that.setData({
          timer: setInterval(function(){
             var lefttime = parseInt((new Date(time.replace(/-/g,"/")).getTime() - new Date().getTime()));
             if(lefttime <= 0) {
               that.setData({
                returnTime:{day:"00",hours:"00",minute:"00",second:"00"}
               })
               clearInterval(that.data.timer);
               return;
             }
  
             var d = parseInt(lefttime /1000 /3600 /24);  //天数
             var h = parseInt(lefttime / 1000 / 3600 % 24); //小时
             var m = parseInt(lefttime / 1000 / 60 % 60);    //分钟
             var s = parseInt(lefttime / 1000  % 60);        //当前的秒
  
             d < 10 ? d = "0" + d : d;
             h < 10 ? h = "0" + h : h;
             m < 10 ? m = "0" + m : m;
             s < 10 ? s = "0" + s : s;
  
             that.setData({
              returnTime:{ day: d, hours: h, minute: m, second:s }
             })
          },1000)
        })
  },
  goShare() {
    let that = this
    let userInfo = wx.getStorageSync('loginMsg').userInfo
    console.log('userInfo', userInfo)
    let partnerPhoto =  userInfo.icon
    let cutGoodsPicture = that.data.imgUrl + that.data.detailData.cutGoodsPicture
    let cutPriceGroupId = that.data.detailData.id
    //砍价成功通知订阅
    app.cutPriceNotifySubscribe(()=>{
      wx.getImageInfo({
        src:  cutGoodsPicture,
        success: function (res) {
          that.setData({
            goodsImgUrl: res.path
          })
        }
      })
      wx.getImageInfo({
        src:  partnerPhoto,
        success: function (res) {
          that.setData({
            headerImgUser: res.path
          })
        }
      })
      that.setData({
        userInfo: userInfo,
        activityShareDlg: true
      })
      that.getQrcode()
    }, cutPriceGroupId)
  },
  // 查看更多
  seeMore() {
    this.setData({
      friendsList: friends
    })
  },
  // 获取小程序码
  getQrcode() {
    var that = this
    var groupId = that.data.detailData.id //团id
    let cutActivityId = that.data.detailData.cutActivityId
    var userId = wx.getStorageSync('loginMsg').userId
    let path = `packageLive/pages/cutPrice/detail/detail`
    var parms = {
      page: path,
      scene: JSON.stringify({
        userId: userId,
        id: groupId
      })
    }
    // 保存分享记录
    app.insertShareRecord(path, null, cutActivityId, 'cutPrice', userId)
    app.reqFun.requestJson('POST', QRCode, parms, (res) => {
      if (res.data.success == 1) {
        that.setData({
          shearImg: 'data:image/png;base64,' + res.data.data,
          modelPopup: 'shear-pop-download'
        })
        that.send_code('data:image/png;base64,' + res.data.data)
      }
    })
  },
  send_code(code) { //base64图片转本地缓存图片
    var that = this;
    const fs = wx.getFileSystemManager();
    //随机定义路径名称
    var times = new Date().getTime();
    var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
    //将base64图片写入
    fs.writeFile({
      filePath: codeimg,
      data: code.slice(22),
      encoding: 'base64',
      success: () => {
        //写入成功了的话，新的图片路径就能用了
        that.setData({
          codeImg: codeimg
        })
      }
    });
  },
  //分享商品海报
  downloadCanvas: function (e) {
    let that = this
    app.getLogin((re)=>{
      if(re){
        wx.showLoading({
          title: '图片生成中···',
        })
        var userInfo = that.data.userInfo
        console.log('userInfo', userInfo)
        var headerImgUser = that.data.headerImgUser
        var headerNameUser = userInfo.nickname
        var detailData = that.data.detailData
        var goodsImgUrl = that.data.goodsImgUrl 
        var codeImg = that.data.codeImg
        // 
        const ctx = wx.createCanvasContext('shareGoods')

        ctx.save();
        ctx.beginPath()     //头像绘制
        ctx.setFillStyle('#fff')
        ctx.fillRect(0, 0, 300, 322)
        ctx.arc(30, 25, 20, 0, 2*Math.PI)
        ctx.clip()
        ctx.drawImage(headerImgUser, 10, 5, 40, 40)
        ctx.restore()
        ctx.beginPath()
        ctx.setFillStyle('#333')
        ctx.font = "bold 13px Arial"
        var nickNameWidth = ctx.measureText(headerNameUser).width
        ctx.fillText(headerNameUser, 65,20, nickNameWidth)
        ctx.fillText('向您推荐',65+nickNameWidth+20,20)
        ctx.setFillStyle('#888')
        ctx.font = "200 12px Arial"
        ctx.fillText('发现一件好物,来帮我砍价拿吧',65,40)

        ctx.beginPath() // 商品信息
        ctx.fillStyle = '#F4F6F5'
        ctx.fillRect(10, 60, 280, 130)
 
        ctx.beginPath()
        ctx.drawImage(goodsImgUrl, 20, 70, 110, 110)

        ctx.beginPath()
        ctx.setFillStyle('#333')
        ctx.font = "bold 14px Arial"
        // ctx.fillText(detailData.cutGoodsName, 140,90, 135)
        var name = detailData.cutGoodsName //插入商品名称
        var txtWidth = ctx.measureText(name).width
        var textToHeight = 90
        if (txtWidth < 135) {
          ctx.fillText(name, 140, textToHeight + 5)
          textToHeight = textToHeight + 20
        } else { //处理插入商品名称过长
          var row = []
          var n = Math.ceil(135 / 16)
          for (var i = 0, l = name.length; i < l / n; i++) {
            var a = name.slice(n * i, n * (i + 1));
            row.push(a);
          }
          for (var b = 0; b < row.length; b++) {
            ctx.fillText(row[b], 140, textToHeight)
            textToHeight = textToHeight + 20
          }
        }
        ctx.setFillStyle('#F15643')
        ctx.font = "bold 12px Arial"
        ctx.fillText('砍后最低价 ¥'+detailData.cutMiniPrice, 140,textToHeight+20, 135)
        ctx.setFillStyle('#999999')
        ctx.font = "12px Arial"
        ctx.fillText('¥'+detailData.originalPrice, 140,textToHeight+40, 135)

        ctx.beginPath()     //小程序码
        ctx.drawImage(that.data.codeImg, 50, 200, 80, 80)
        ctx.restore()

        ctx.beginPath()
        ctx.font = "12px Arial"
        ctx.setFillStyle('#888888')
        ctx.fillText('长按识别小程序码', 140,230)
        ctx.beginPath()
        ctx.font = "12px Arial"
        ctx.setFillStyle('#888888')
        ctx.fillText('轻松帮好友砍价', 140,250)
        
        // ctx.beginPath() //绘制标签
        // ctx.lineWidth = "1";
        // ctx.strokeStyle = "#F15643";
        // ctx.font = "bold 10px Arial";
      
        // ctx.beginPath() //绘制二维码
        // ctx.drawImage(codeImg, 200, 380, 90, 90)
        // ctx.font = "bold 12px Arial";
        // ctx.setFillStyle('#888')
        // ctx.fillText('长按/扫描识别', 210, 490)
        ctx.draw()
        setTimeout(function () {
          wx.canvasToTempFilePath({ //canvas生成图片
            x: 0,
            y: 0,
            width: 300,
            height: 322,
            canvasId: 'shareGoods',
            success(res) {
              console.log(res.tempFilePath)
              wx.saveImageToPhotosAlbum({     //保存图片到相册
                filePath:res.tempFilePath,
                success:function(e){
                  wx.hideLoading({})
                  wx.showToast({
                    title: '保存图片成功',
                    duration:3000
                  })
                },fail:function(e){
                  wx.hideLoading({})
                  wx.showModal({
                    title: '保存失败',
                    content: '保存图片失败,请点击右上角按钮-设置-开启授权',
                    showCancel:false,
                  })
                }
              })
            }
          })
        }, 4000)
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          } else {
            callback(true)  //低版本微信绑过电话视为已登录
          }
        }
      }
    })
  },

/**
 * 绘制圆角矩形
 * @param {Object} ctx - canvas组件的绘图上下文
 * @param {Number} x - 矩形的x坐标
 * @param {Number} y - 矩形的y坐标
 * @param {Number} w - 矩形的宽度
 * @param {Number} h - 矩形的高度
 * @param {Number} r - 矩形的圆角半径
 * @param {String} [c = 'transparent'] - 矩形的填充色
 */
roundRect(ctx, x, y, w, h, r, c = '#fff') {
    if (w < 2 * r) { r = w / 2; }
    if (h < 2 * r) { r = h / 2; }
 
    ctx.beginPath();
    ctx.fillStyle = c;
 
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + w - r, y);
    ctx.lineTo(x + w, y + r);
 
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
    ctx.lineTo(x + w, y + h - r);
    ctx.lineTo(x + w - r, y + h);
 
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
    ctx.lineTo(x + r, y + h);
    ctx.lineTo(x, y + h - r);
 
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
    ctx.lineTo(x, y + r);
    ctx.lineTo(x + r, y);
 
    ctx.fill();
    ctx.closePath();
},
  shareClose() {
    this.setData({
      activityShareDlg: false
    })
  },
  cutAKnife() {
    let cutPriceGroupId = this.data.detailData.id
    app.reqFun.requestJson('GET',spellApi.cutAKnife+cutPriceGroupId,'',(res)=>{
      if(res.data.success === 1) {
        let data = res.data.data
        this.setData({
          cutAKnifeDlg: true,
          cutAKnifeData: data
        })
      } else {
        this.setData({
          cutAKnifeFailedMsg: res.data.msg,
          cutAKnifeFailedDlg: true
        })
      }
    })
  },
  cutAKnifeFailedClose() {
    this.setData({
      cutAKnifeFailedDlg: false
    })
  },
  cutAKnifeClose() {
    this.getDetail(this.data.detailData.id)
    this.setData({
      cutAKnifeDlg: false
    })
  },
  cutPriceActivity() {
    let cutActivityId = this.data.detailData.cutActivityId
    wx.navigateTo({
      url: '/packageLive/pages/cutPrice/cutPriceActivity/cutPriceActivity?id=' + cutActivityId,
    })
  },
  // 去下单
  placeOrder() {
    let that = this
    let detailData = that.data.detailData
    var goodsNum = detailData.buyNum
    var skus = [{
      skuId: detailData.skuId,
      number: goodsNum
    }]
    var submitdata = {
      sku: skus
    }
    submitdata.omsOrderType = 'CUT_PRICE',
    submitdata.settlementMethod = "BUY_NOW"
    submitdata.groupActivityId = detailData.cutActivityId
    submitdata.groupId = detailData.id
    wx.setStorageSync('submitSku', submitdata)
    wx.navigateTo({
      url: '/packagBuy/pages/confirmOrder/confirmOrder?type=orderOnline',
    })
    that.setData({
      spellVerDlg: false
    })
  },
  orderDetail() {
    let id = this.data.detailData.parentOrderId
    let orderId = this.data.detailData.orderId
    let parentOrderStatus = this.data.detailData.parentOrderStatus
    let orderStatus = this.data.detailData.orderStatus
    let option
    if (parentOrderStatus == '0') {
      option = {
        status: parentOrderStatus,
        id: id
      }
    } else {
      option = {
        status: orderStatus,
        id: id,
        orderId: orderId
      }
    }
    wx.navigateTo({
      url: '/packagMy/pages/personal/myOrder/orderDetail/orderDetail?option=' + JSON.stringify(option)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    if (this.data.groupId) {
      //保存访问足迹
      app.saveAccessFootprint(this.data.footprintGuid, 'cutPriceGroup', this.data.groupId)
    } else {
      //拿到资源id再记录足迹
      var footprintWaitResourceIdTimer = setInterval(()=>{
        if(this.data.groupId){
          //保存访问足迹
          app.saveAccessFootprint(this.data.footprintGuid, 'cutPriceGroup', this.data.groupId)
          clearInterval(footprintWaitResourceIdTimer)
        }
      }, 100)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that=this
    var cutGoodsName = that.data.detailData.cutGoodsName
    var cutActivityId = that.data.detailData.cutActivityId
    let path = `/packageLive/pages/cutPrice/detail/detail`
    // let query = `?id=${id}`
    let userId = wx.getStorageSync('loginMsg').userId
    let query = `?id=${that.data.groupId}&hid=${wx.getStorageSync('loginMsg').userId}`
    // 保存分享记录
    app.insertShareRecord(path, query, cutActivityId, 'cutPrice', userId)
    return {
      title: '发现一件好物,来帮我砍价拿吧',
      path: path + query
    }
  },
  //展开合伙人信息
  showPartnerAll: function () {
    let isShowPartnerAll;
    if (this.data.isShowPartnerAll == 1) {
      isShowPartnerAll = 0;
    } else {
      isShowPartnerAll = 1;
    }
    this.setData({
      isShowPartnerAll: isShowPartnerAll,
    })
  },
  //展示合伙人二维码
  partnerCode: function (e) {
    // this.setData({
    //   showPartnerCodePop: true,
    // })
    let codeImg=e.target.dataset.url
    wx.previewImage({
      urls:[codeImg],
      current: codeImg, // 当前显示图片的http链接
     })
  },
  //关闭合伙人二维码
  closeCodePop: function () {
    this.setData({
      showPartnerCodePop: false,
    })
  },
  //拨打合伙人电话
  partnerPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone,
    })
  }
})